import React, { useState, useEffect } from 'react';
import {
  listStoragePools,
  createStoragePool,
  deleteStoragePool,
  listVolumes,
  createVolume,
  deleteVolume,
  startStoragePool,
  stopStoragePool,
  refreshStoragePool
} from '../api/client';
import './Storage.css';

// 类型定义
interface StoragePool {
  uuid: string;
  name: string;
  state: 'active' | 'inactive' | 'building' | 'degraded' | 'inaccessible';
  type: string;
  capacity: number;
  allocation: number;
  available: number;
  autostart: boolean;
  persistent: boolean;
  path?: string;
}

interface Volume {
  name: string;
  key: string;
  path: string;
  type: string;
  capacity: number;
  allocation: number;
  pool: string;
}

// 存储池操作类型
type PoolAction = 'start' | 'stop' | 'refresh' | 'delete';

const StorageV2: React.FC = () => {
  const [pools, setPools] = useState<StoragePool[]>([]);
  const [volumes, setVolumes] = useState<Record<string, Volume[]>>({});
  const [selectedPoolUUID, setSelectedPoolUUID] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [searchTerm, setSearchTerm] = useState('');
  const [showCreatePool, setShowCreatePool] = useState(false);
  const [showCreateVolume, setShowCreateVolume] = useState(false);
  const [actionInProgress, setActionInProgress] = useState<string | null>(null);

  // 新存储池表单状态
  const [newPool, setNewPool] = useState({
    name: '',
    type: 'dir',
    target: '',
    source: ''
  });

  // 新存储卷表单状态
  const [newVolume, setNewVolume] = useState({
    name: '',
    capacity: 10,
    format: 'qcow2'
  });

  // 加载存储池
  const loadStoragePools = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await listStoragePools();
      setPools(response.data.pools || []);
    } catch (err) {
      console.error('Failed to load storage pools:', err);
      setError('Failed to load storage pools. Please make sure the API server is running.');
    } finally {
      setLoading(false);
    }
  };

  // 加载存储卷
  const loadVolumes = async (poolUUID: string) => {
    try {
      const response = await listVolumes(poolUUID);
      setVolumes(prev => ({
        ...prev,
        [poolUUID]: response.data.volumes || []
      }));
    } catch (err) {
      console.error(`Failed to load volumes for pool ${poolUUID}:`, err);
    }
  };

  // 执行存储池操作
  const handlePoolAction = async (poolUUID: string, action: PoolAction) => {
    try {
      setActionInProgress(`${action}-${poolUUID}`);

      switch (action) {
        case 'start':
          await startStoragePool(poolUUID);
          break;
        case 'stop':
          await stopStoragePool(poolUUID);
          break;
        case 'refresh':
          await refreshStoragePool(poolUUID);
          break;
        case 'delete':
          const pool = pools.find(p => p.uuid === poolUUID);
          if (pool && window.confirm(`确定要删除存储池 "${pool.name}" 吗？`)) {
            await deleteStoragePool(poolUUID);
          }
          break;
      }

      // 刷新数据
      await loadStoragePools();
      if (selectedPoolUUID === poolUUID) {
        await loadVolumes(poolUUID);
      }
    } catch (err) {
      console.error(`Failed to ${action} pool ${poolUUID}:`, err);
      alert(`操作失败: ${err}`);
    } finally {
      setActionInProgress(null);
    }
  };

  // 创建存储池
  const handleCreatePool = async () => {
    try {
      const poolData = {
        name: newPool.name,
        type: newPool.type,
        target: newPool.target,
        source: newPool.source || undefined
      };

      await createStoragePool(poolData);
      setShowCreatePool(false);
      setNewPool({ name: '', type: 'dir', target: '', source: '' });
      await loadStoragePools();
    } catch (err) {
      console.error('Failed to create storage pool:', err);
      alert(`创建存储池失败: ${err}`);
    }
  };

  // 创建存储卷
  const handleCreateVolume = async () => {
    if (!selectedPoolUUID) return;

    try {
      const volumeData = {
        name: newVolume.name,
        capacity: newVolume.capacity * 1024 * 1024 * 1024, // GB to bytes
        format: newVolume.format
      };

      await createVolume(selectedPoolUUID, volumeData);
      setShowCreateVolume(false);
      setNewVolume({ name: '', capacity: 10, format: 'qcow2' });
      await loadVolumes(selectedPoolUUID);
    } catch (err) {
      console.error('Failed to create volume:', err);
      alert(`创建存储卷失败: ${err}`);
    }
  };

  // 删除存储卷
  const handleDeleteVolume = async (poolUUID: string, volumeName: string) => {
    if (window.confirm(`确定要删除存储卷 "${volumeName}" 吗？`)) {
      try {
        await deleteVolume(poolUUID, volumeName);
        await loadVolumes(poolUUID);
      } catch (err) {
        console.error('Failed to delete volume:', err);
        alert(`删除存储卷失败: ${err}`);
      }
    }
  };

  // 格式化字节大小
  const formatBytes = (bytes: number) => {
    const gb = bytes / (1024 * 1024 * 1024);
    return `${gb.toFixed(1)} GB`;
  };

  // 获取使用百分比
  const getUsagePercentage = (allocation: number, capacity: number) => {
    return capacity > 0 ? Math.round((allocation / capacity) * 100) : 0;
  };

  // 获取状态颜色
  const getStatusColor = (state: string) => {
    switch (state) {
      case 'active': return 'success';
      case 'inactive': return 'secondary';
      case 'building': return 'warning';
      case 'degraded': return 'danger';
      case 'inaccessible': return 'danger';
      default: return 'secondary';
    }
  };

  // 获取状态文本
  const getStatusText = (state: string) => {
    switch (state) {
      case 'active': return '活跃';
      case 'inactive': return '非活跃';
      case 'building': return '构建中';
      case 'degraded': return '降级';
      case 'inaccessible': return '无法访问';
      default: return '未知';
    }
  };

  // 过滤存储池
  const filteredPools = pools.filter(pool =>
    pool.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
    pool.type.toLowerCase().includes(searchTerm.toLowerCase())
  );

  useEffect(() => {
    loadStoragePools();
  }, []);

  if (loading) {
    return (
      <div className="storage-page">
        <div className="page-header">
          <div className="header-content">
            <h1>存储管理</h1>
            <div className="header-meta">
              <span className="pool-count">{pools.length} 个存储池</span>
              <span className="total-capacity">
                总计: {formatBytes(pools.reduce((sum, pool) => sum + pool.capacity, 0))}
              </span>
            </div>
          </div>
          <div className="header-actions">
            <button className="btn btn-primary" disabled>+ 新建存储池</button>
            <button className="btn btn-secondary" disabled>⟳</button>
          </div>
        </div>
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>正在加载存储池...</p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="storage-page">
        <div className="page-header">
          <div className="header-content">
            <h1>存储管理</h1>
            <div className="header-meta">
              <span className="pool-count">{pools.length} 个存储池</span>
              <span className="total-capacity">
                总计: {formatBytes(pools.reduce((sum, pool) => sum + pool.capacity, 0))}
              </span>
            </div>
          </div>
          <div className="header-actions">
            <button className="btn btn-primary" disabled>+ 新建存储池</button>
            <button className="btn btn-secondary" onClick={loadStoragePools}>
              ↻ 重试
            </button>
          </div>
        </div>
        <div className="error-card">
          <div className="error-icon">⚠️</div>
          <h3>连接错误</h3>
          <p>{error}</p>
          <button className="btn btn-primary" onClick={loadStoragePools}>
            重新加载
          </button>
        </div>
      </div>
    );
  }

  return (
    <div className="storage-page">
      {/* 页面头部 */}
      <div className="page-header">
        <div className="header-content">
          <h1>存储管理</h1>
          <div className="header-meta">
            <span className="pool-count">{pools.length} 个存储池</span>
            <span className="total-capacity">
              总计: {formatBytes(pools.reduce((sum, pool) => sum + pool.capacity, 0))}
            </span>
          </div>
        </div>
        <div className="header-actions">
          <button
            className="btn btn-primary"
            onClick={() => setShowCreatePool(true)}
          >
            + 新建存储池
          </button>
          <button
            className="btn btn-secondary"
            onClick={loadStoragePools}
            disabled={loading}
          >
            {loading ? '⟳' : '↻'}
          </button>
        </div>
      </div>

      {/* 搜索栏 */}
      <div className="search-bar">
        <input
          type="text"
          placeholder="搜索存储池..."
          value={searchTerm}
          onChange={(e) => setSearchTerm(e.target.value)}
          className="search-input"
        />
      </div>

      {/* 存储池网格 */}
      <div className="storage-grid">
        {filteredPools.map((pool) => (
          <div key={pool.uuid} className="storage-card">
            {/* 卡片头部 */}
            <div className="card-header">
              <div className="pool-info">
                <h3 className="pool-name">{pool.name}</h3>
                <div className="pool-meta">
                  <span className={`status-badge ${getStatusColor(pool.state)}`}>
                    {getStatusText(pool.state)}
                  </span>
                  <span className="pool-type">{pool.type}</span>
                </div>
              </div>
              <div className="pool-actions">
                <button
                  className="btn btn-sm btn-secondary"
                  onClick={() => handlePoolAction(pool.uuid, 'refresh')}
                  disabled={actionInProgress === `refresh-${pool.uuid}`}
                  title="刷新存储池"
                >
                  ↻
                </button>
                {pool.state === 'active' ? (
                  <button
                    className="btn btn-sm btn-warning"
                    onClick={() => handlePoolAction(pool.uuid, 'stop')}
                    disabled={actionInProgress === `stop-${pool.uuid}`}
                    title="停止存储池"
                  >
                    ⏸️
                  </button>
                ) : (
                  <button
                    className="btn btn-sm btn-success"
                    onClick={() => handlePoolAction(pool.uuid, 'start')}
                    disabled={actionInProgress === `start-${pool.uuid}`}
                    title="启动存储池"
                  >
                    ▶️
                  </button>
                )}
                <button
                  className="btn btn-sm btn-danger"
                  onClick={() => handlePoolAction(pool.uuid, 'delete')}
                  disabled={actionInProgress === `delete-${pool.uuid}`}
                  title="删除存储池"
                >
                  🗑️
                </button>
              </div>
            </div>

            {/* 容量信息 */}
            <div className="capacity-section">
              <div className="capacity-header">
                <span>容量</span>
                <span>
                  {formatBytes(pool.allocation)} / {formatBytes(pool.capacity)}
                </span>
              </div>
              <div className="progress-bar">
                <div
                  className="progress-fill"
                  style={{
                    width: `${getUsagePercentage(pool.allocation, pool.capacity)}%`,
                    backgroundColor: getUsagePercentage(pool.allocation, pool.capacity) > 80 ? 'var(--danger-color)' : 'var(--success-color)'
                  }}
                ></div>
              </div>
              <div className="capacity-footer">
                <span>可用: {formatBytes(pool.available)}</span>
                <span>{getUsagePercentage(pool.allocation, pool.capacity)}% 已使用</span>
              </div>
            </div>

            {/* 详细信息 */}
            <div className="pool-details">
              <div className="detail-row">
                <span className="detail-label">UUID:</span>
                <span className="detail-value">{pool.uuid}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">自动启动:</span>
                <span className="detail-value">{pool.autostart ? '是' : '否'}</span>
              </div>
              <div className="detail-row">
                <span className="detail-label">持久化:</span>
                <span className="detail-value">{pool.persistent ? '是' : '否'}</span>
              </div>
            </div>

            {/* 存储卷部分 */}
            <div className="volumes-section">
              <div className="volumes-header">
                <h4>存储卷</h4>
                <button
                  className="btn btn-sm btn-primary"
                  onClick={() => {
                    setSelectedPoolUUID(pool.uuid);
                    setShowCreateVolume(true);
                  }}
                >
                  + 新建存储卷
                </button>
              </div>

              {selectedPoolUUID === pool.uuid && volumes[pool.uuid] ? (
                <div className="volumes-list">
                  {volumes[pool.uuid].map((volume) => (
                    <div key={volume.key} className="volume-item">
                      <div className="volume-info">
                        <span className="volume-name">{volume.name}</span>
                        <span className="volume-size">{formatBytes(volume.capacity)}</span>
                      </div>
                      <div className="volume-actions">
                        <button
                          className="btn btn-sm btn-danger"
                          onClick={() => handleDeleteVolume(pool.uuid, volume.name)}
                          title="删除存储卷"
                        >
                          🗑️
                        </button>
                      </div>
                    </div>
                  ))}
                </div>
              ) : (
                <button
                  className="btn btn-link"
                  onClick={() => {
                    setSelectedPoolUUID(pool.uuid);
                    loadVolumes(pool.uuid);
                  }}
                >
                  查看存储卷
                </button>
              )}
            </div>
          </div>
        ))}
      </div>

      {/* 空状态 */}
      {pools.length === 0 && (
        <div className="empty-state">
          <div className="empty-icon">💾</div>
          <h3>暂无存储池</h3>
          <p>创建您的第一个存储池开始使用。</p>
          <button
            className="btn btn-primary"
            onClick={() => setShowCreatePool(true)}
          >
            创建存储池
          </button>
        </div>
      )}

      {/* 创建存储池模态框 */}
      {showCreatePool && (
        <div className="modal-overlay" onClick={() => setShowCreatePool(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>创建存储池</h2>
              <button
                className="modal-close"
                onClick={() => setShowCreatePool(false)}
              >
                ✕
              </button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">存储池名称</label>
                <input
                  type="text"
                  className="form-input"
                  value={newPool.name}
                  onChange={(e) => setNewPool({...newPool, name: e.target.value})}
                  placeholder="输入存储池名称"
                />
              </div>
              <div className="form-group">
                <label className="form-label">存储池类型</label>
                <select
                  className="form-select"
                  value={newPool.type}
                  onChange={(e) => setNewPool({...newPool, type: e.target.value})}
                >
                  <option value="dir">目录</option>
                  <option value="fs">文件系统</option>
                  <option value="netfs">网络文件系统</option>
                  <option value="disk">磁盘</option>
                  <option value="iscsi">iSCSI</option>
                  <option value="logical">LVM</option>
                </select>
              </div>
              <div className="form-group">
                <label className="form-label">目标路径</label>
                <input
                  type="text"
                  className="form-input"
                  value={newPool.target}
                  onChange={(e) => setNewPool({...newPool, target: e.target.value})}
                  placeholder="/var/lib/libvirt/images"
                />
              </div>
              {newPool.type === 'disk' && (
                <div className="form-group">
                  <label className="form-label">源设备</label>
                  <input
                    type="text"
                    className="form-input"
                    value={newPool.source}
                    onChange={(e) => setNewPool({...newPool, source: e.target.value})}
                    placeholder="/dev/sdb"
                  />
                </div>
              )}
            </div>
            <div className="modal-footer">
              <button
                className="btn btn-secondary"
                onClick={() => setShowCreatePool(false)}
              >
                取消
              </button>
              <button
                className="btn btn-primary"
                onClick={handleCreatePool}
                disabled={!newPool.name || !newPool.target}
              >
                创建存储池
              </button>
            </div>
          </div>
        </div>
      )}

      {/* 创建存储卷模态框 */}
      {showCreateVolume && selectedPoolUUID && (
        <div className="modal-overlay" onClick={() => setShowCreateVolume(false)}>
          <div className="modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="modal-header">
              <h2>在 {pools.find(p => p.uuid === selectedPoolUUID)?.name || '未知存储池'} 中创建存储卷</h2>
              <button
                className="modal-close"
                onClick={() => setShowCreateVolume(false)}
              >
                ✕
              </button>
            </div>
            <div className="modal-body">
              <div className="form-group">
                <label className="form-label">存储卷名称</label>
                <input
                  type="text"
                  className="form-input"
                  value={newVolume.name}
                  onChange={(e) => setNewVolume({...newVolume, name: e.target.value})}
                  placeholder="输入存储卷名称"
                />
              </div>
              <div className="form-group">
                <label className="form-label">大小 (GB)</label>
                <input
                  type="number"
                  className="form-input"
                  value={newVolume.capacity}
                  onChange={(e) => setNewVolume({...newVolume, capacity: parseInt(e.target.value) || 0})}
                  min="1"
                  placeholder="10"
                />
              </div>
              <div className="form-group">
                <label className="form-label">格式</label>
                <select
                  className="form-select"
                  value={newVolume.format}
                  onChange={(e) => setNewVolume({...newVolume, format: e.target.value})}
                >
                  <option value="qcow2">QCOW2</option>
                  <option value="raw">Raw</option>
                  <option value="vmdk">VMDK</option>
                </select>
              </div>
            </div>
            <div className="modal-footer">
              <button
                className="btn btn-secondary"
                onClick={() => setShowCreateVolume(false)}
              >
                取消
              </button>
              <button
                className="btn btn-primary"
                onClick={handleCreateVolume}
                disabled={!newVolume.name || newVolume.capacity <= 0}
              >
                创建存储卷
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default StorageV2;